package practice_2025_9.practice_9_17;

class Solution {
    /**
     * 长度最小的子数组
     * @param target
     * @param nums
     * @return
     */
    public int minSubArrayLen(int target, int[] nums) {
        // 找到数组中和 >= target 的最小长度连续子数组
        int sum = 0;
        int len = Integer.MAX_VALUE;
        for(int left = 0, right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                len = Math.min(len, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        if (len == Integer.MAX_VALUE) {
            return 0;
        } else {
            return len;
        }
    }

    int[] dx = {0, 0, -1, 1};
    int[] dy = {1, -1, 0, 0};
    int m = 0;
    int n = 0;
    int[][] record;

    /**
     * 矩阵中的最长递增路径
     * @param matrix
     * @return
     */
    public int longestIncreasingPath(int[][] matrix) {
        // 最长递增路径
        m = matrix.length;
        n = matrix[0].length;
        record = new int[m][n];
        int max = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                max = Math.max(max, dfs(matrix, i, j));
            }
        }
        return max;
    }
    public int dfs(int[][] matrix, int x, int y) {
        if (record[x][y] != 0) {
            return record[x][y];
        }
        int count = 0;
        for(int i = 0; i < dx.length; i++) {
            int nextX = dx[i] + x;
            int nextY = dy[i] + y;
            if (nextX >= 0 && nextX < m
                    && nextY >= 0 && nextY < n && matrix[nextX][nextY] > matrix[x][y]) {
                count = Math.max(count, dfs(matrix, nextX, nextY));
            }
        }
        count += 1;
        record[x][y] = count;
        return count;
    }
}